<?php

namespace app\common\model\banxi\learn;

use app\common\enums\AntiForgettingFlagEnum;
use app\common\enums\WordLearnTypeEnum;
use app\common\model\common\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 上课学习词汇记录
 */
class LearnSkWordRecord extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_learn_sk_word_record';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'wordLearnTypeCn',
        'antiForgettingFlagCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'skRecordId' => 'string',
        'studentId' => 'string',
        'trainerId' => 'string',
        'courseId' => 'string',
        'isForget' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    public function getAccountTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['accountType'] ?? '');
        return (new WordLearnTypeEnum())->getDescription($value) ?? '';
    }

    public function getAntiForgettingFlagCnAttr($value, $data)
    {
        $value = $value ?: ($data['antiForgettingFlag'] ?? '');
        return (new AntiForgettingFlagEnum())->getDescription($value) ?? '';
    }


    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    /**
     * 获取教练累计教词
     * @param int $trainerId 教练ID
     * @return int 教授单词总数
     */
    public function getTotalWordByTrainerId($trainerId)
    {
        $count = $this->where('studentId', $trainerId)
            ->where('wordLearnType', WordLearnTypeEnum::E1)
            ->group('studentId, word')
            ->distinct(true)
            ->field('word')
            ->count();

        return $count;
    }

    /**
     * 提交上课学习单词
     */
    public function submitLearnWord($skId, $studentId, $studentOrgId, $trainerId, $courseId, $learnWordList, $learnWordMemorizeRecordList, $antiForgettingFlag, $learnNewOrRemember)
    {
        $words = array_column($learnWordList, 'word');

        // 查询已有记录
        $wordRecordList = $this
            ->where('skRecordId', $skId)
            ->whereIn('word', $words)
            ->select();

        $saveList = [];
        $updateList = [];

        foreach ($learnWordList as $learnWord) {
            $word = $learnWord['word'];

            // 查找单词记忆记录
            $wordMemorizeRecord = null;
            foreach ($learnWordMemorizeRecordList as $record) {
                if ($record['word'] === $word) {
                    $wordMemorizeRecord = $record;
                    break;
                }
            }

            // 确定单词学习类型
            $wordLearnType = '';
            if ($learnNewOrRemember && $wordMemorizeRecord == null) {
                // 学新且该单词未学习过，认为是本来就认识
                $wordLearnType = WordLearnTypeEnum::E3;
            } else {
                // 识记，如果单词学习过则为复习
                $wordLearnType = $wordMemorizeRecord != null ? WordLearnTypeEnum::E2 : WordLearnTypeEnum::E1;
            }

            // 查询本次上课期间是否学习过该单词
            $wordRecord = null;
            foreach ($wordRecordList as $record) {
                if ($record['word'] === $word) {
                    $wordRecord = $record;
                    break;
                }
            }
            //            Log::info('如果未学习过该单词或课程studentId:'.$studentId);
            // 如果未学习过该单词或课程/学习类型不同，则新建记录
            if ($wordRecord == null ||
                ($wordRecord['course_id'] != $courseId && $wordRecord['word_learn_type'] != $wordLearnType)) {
                $wordRecord = [
                    'skRecordId' => $skId,
                    'studentId' => $studentId,
                    'studentOrgId' => $studentOrgId,
                    'trainerId' => $trainerId,
                    'word' => $word,
                    'wordLearnType' => $wordLearnType
                ];
            }

            $wordRecord['courseId'] = $courseId;
            if ($wordRecord['wordLearnType'] == $wordLearnType) {
                $wordRecord['isForget'] = !$learnWord['result'];
            }

            // 抗遗忘逻辑
            if ($antiForgettingFlag == AntiForgettingFlagEnum::E2 && $wordLearnType == WordLearnTypeEnum::E2) {
                $wordRecord['antiForgettingFlag'] = AntiForgettingFlagEnum::E1;
            } else {
                $wordRecord['antiForgettingFlag'] = $antiForgettingFlag;
            }

            if (!isset($wordRecord['id'])) {
                $wordRecord['createTime'] = time();
                $wordRecord['updateTime'] = time();
                $saveList[] = $wordRecord;
            } else {
                $wordRecord['updateTime'] = time();
                $updateList[] = $wordRecord;
            }
        }

        // 批量插入新记录
        if (!empty($saveList)) {
            $this->insertAll($saveList);
        }

        // 批量更新记录
        if (!empty($updateList)) {
            foreach ($updateList as $update) {
                $this->update($update, ['id' => $update['id']]);
            }
        }
    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------
}